<template>
  <div :id="'media-layout-' + item.type" class="media-layout">
    <el-button v-if="isPop" class="btn-close" size="small" @click.stop="onClose">
      <el-icon><i class="jy-icon-layer-closed"></i></el-icon>
    </el-button>
    <div class="media-layout-handle clearfixed">
      <div class="handle-upload flex-end left">
        <file-upload :url="url" :fileUploadData="fileUploadData" :item="item"></file-upload>
        <span class="handle-upload-tips">{{item.tips}}</span>
      </div>
      <div v-if="!isPop" class="handle-mg flex-end right">
        <!-- <el-button class="clear-ed handle-mg-btn tab-over" type="text" icon="Plus">添加分组</el-button> -->
        <div v-if="isDisplayIcon">
          <el-button class="clear-ed handle-mg-btn tab-over" type="text" @click.stop="onCancel" >取消</el-button>
          <el-button class="clear-ed handle-mg-btn tab-over" type="text" @click.stop="onDelete" v-if="isDisplayIcon">删除</el-button>
        </div>
        <el-button class="clear-ed handle-mg-btn tab-over" type="text" @click.stop="onManage" v-else>管理</el-button>
      </div>
      <div v-if="!isPop" class="handle-mg flex-end right margin-top-bottom-10 clear">
        <el-input type="number" size="small" class="width-100-px margin-right-10" v-model="loadSiteId" placeholder="站点id"></el-input>
        <el-button type="primary" size="small" @click="onLoadBySiteId">加载指定站点图片</el-button>
        <el-button type="success" size="small" @click="onLoadAllImgs">加载所有图片</el-button>
      </div>
    </div>

    <div class="media-layout-group">
      <!-- <div class="group-tabs">
        <a v-for="(item, index) in lists"
          :key="index"
          href="javascript:;"
          class="tab-over"
          :class="tabGroup==item.tab?'is-group':''"
          @click.stop="click2ChangeGroup(item.tab)">
            <span>{{item.tabTxt}}</span>
        </a>
      </div> -->
      <div v-if="mediaData" class="infinite-list-wrapper">
        <div class="group-lists" v-infinite-scroll="onLoad" infinite-scroll-disabled="disabled">
          <div
            v-for="(item_, index) in mediaData.list"
            :key="item_.id + '-' + index">
            <div class="group-item" @click.stop="onAddComponent($event, item_, index)">
              <div v-if="item_.loading" v-loading="item_.loading" class="group-item-con"></div>
              <div v-else class="group-item-con">
                <div v-if="item.type==MEDIAS.image.type" class="popover-img-con">
                  <img v-lazy="item_.url" @click="onConsoleUrl(item_.url)">
                  <el-popover
                    placement="right"
                    :width="previewImgHei"
                    trigger="hover">
                    <img v-lazy="item_.url" class="popover-img">
                    <el-input v-model="item_.name"></el-input>
                    <el-input v-model="item_.url"></el-input>
                    <template #reference>
                      <el-button size="small">
                        <el-icon><i class="jy-icon-view"></i></el-icon>
                      </el-button>
                    </template>
                  </el-popover>
                </div>
                <div v-else-if="item.type==MEDIAS.video.type" class="popover-img-con">
                  <p class="width-height-100 clear-ed">
                    <i class="jy-icon-video1"></i>
                  </p>
                  <el-popover
                    placement="right"
                    :width="previewImgHei"
                    trigger="hover">
                    <el-input v-model="item_.name"></el-input>
                    <el-input v-model="item_.url"></el-input>
                    <template #reference>
                      <el-button size="small">
                        <el-icon><i class="jy-icon-view"></i></el-icon>
                      </el-button>
                    </template>
                  </el-popover>
                </div>
                <!-- <img v-else-if="item.type==MEDIAS.video.type" :src="`${env.publicPath}images/btn-play.png`" alt=""> -->
                <div v-else class="clear-ed popover-img-con">
                  <p class="width-height-100 clear-ed">
                    <i class="jy-icon-music"></i>
                  </p>
                  <el-popover
                    placement="right"
                    :width="previewImgHei"
                    trigger="hover">
                    <el-input v-model="item_.name"></el-input>
                    <el-input v-model="item_.url"></el-input>
                    <template #reference>
                      <el-button class="font-12" size="small">
                        <el-icon><i class="jy-icon-view"></i></el-icon>
                      </el-button>
                    </template>
                  </el-popover>
                </div>
                <div :class="{active:item_.isDelete, 'delete-icon': true}" v-if="isDisplayIcon"></div>
              </div>
            </div>
            <span :title="item_.name" class="group-item-name txt_nowrap txt_ellipsis">{{item_.name}}</span>
          </div>
        </div>
        <p v-if="loading" class="text-center font-12 color-white">加载中...</p>
        <p v-if="noMore" class="text-center font-12 color-white">没有更多了</p>
      </div>
    </div>
    <div v-if="isPop" :class="{'triangle-border-right': isPop }"></div>
  </div>
</template>

<script>
  import FileUpload from '@/views/components/file-upload.vue'
  import { mapActions, mapState, mapGetters } from 'vuex'
  import { getImgRatio } from '@/plugins/utils'
  import { bgPositionStyle } from '@/store/utils'
  import { MEDIAS, COMPONENT_TYPES } from '@/common/const'
  import { MOBILE_WID_HEI } from '@/common/const-dif'
  import { fileUploadUrl } from '@/api/api'
  import { reactive } from 'vue'

  export default {
    props: {
      item: Object,
      isPop: Boolean
    },
    setup () {
      const state =  reactive({
        isDisplayIcon: false,
        //medialist
        loading: false,
        loadSiteId: 0,
      })
      const state_ = {
        url: fileUploadUrl,
        tabGroup: 0,
        MEDIAS: MEDIAS,
        previewImgHei: 400,
        isResetList: false,
      }
      _.merge(state, state_)
      return state
    },
    components: {
      FileUpload,
    },
    computed: {
      ...mapState({
        page: (state) => state.components.currentPage,
        fileUploadData: state => state.components.fileUploadData,
        componentData: state => state.components.currentComponentData,
        siteAttrs: state => state.components.attrs,
        mediaPop: state => state.mediaPop,
        mediaAllData: state => state.user.mediaAllData,
        siteList: state => state.user.myLists,
        site_id: state => state.components.id,
      }),
      ...mapGetters("components", {
        isSite: "isSite",
      }),
      mediaData(){
        return this.mediaAllData[this.item.type]
      },
      siteNum(){
        return this.siteList.length;
      },
      noMore () {
        let mediaData_ = this.mediaData;
        return mediaData_.list.length >= mediaData_.total;
      },
      disabled () {
        return this.loading || this.noMore
      }
    },
    mounted() {
      this.loadSiteId = parseInt(this.site_id);
    },
    methods: {
      ...mapActions({
        addComponent: 'components/addComponent',
        updateCurrentComponentData: 'components/updateCurrentComponentData',
        updateWbComponentItem: 'wbComponents/updateWbComponentItem',
        updateComponentItem: 'components/updateComponentItem',

        updatePageAttrs: 'components/updatePageAttrs',
        updatePageStyles: 'components/updatePageStyles',

        updateComponentStyles: 'components/updateComponentStyles',

        updateSiteAttrs: "components/updateSiteAttrs",
        updateSiteStyles: "components/updateSiteStyles",

        deleteMediaList: "user/deleteMediaList",
        updateMediaItem: 'user/updateMediaItem',
        hiddenMediaPop: 'hiddenMediaPop',

        getMediaData: "user/getMediaData",
      }),
      onConsoleUrl(){
        // console.log(url + ',')
      },
      onLoadAllImgs(){
        this.loadSiteId = 0;
        this.onLoad();
      },  
      onLoadBySiteId(){
        this.isResetList = true;
        this.onLoad();
      },
      onLoad() {
        if(this.loadSiteId == -1) {
          return
        }
        this.loading = true;
        let mediaData_ = this.mediaData
        let nextPage = mediaData_.page + 1;
        let pageSize = mediaData_.pageSize;
        if(this.isResetList){
          nextPage = 1;
        }
        let callback = () => {
          // 数据全部加载完成
          this.loading = false;
        }
        if(nextPage <= mediaData_.totalPage){
          if(this.loadSiteId && parseInt(this.loadSiteId) > 0){
            this.getMediaData({ page: nextPage, pageSize, type: this.item.type, site_id: this.loadSiteId, isResetList: this.isResetList, callback})
          }else{
            this.getMediaData({ page: nextPage, pageSize, type: this.item.type, isResetList: this.isResetList, callback})
          }
          this.isResetList = false;
        }
      },
      onManage(){
        this.isDisplayIcon = true;
      },
      onDelete(){
        let items = [];
        this.mediaData.list.forEach(item => {
          if(item.isDelete){
            items.push(item.id);
          }
        })
        this.deleteMediaList({type: this.item.type, items});
      },
      onCancel(){
        this.isDisplayIcon = false;
      },
      onAddComponent(e, item, index){
        let url = item.url;
        if(this.isPop){
          if(!this.componentData){
            // let styles = {backgroundImage:'url(' + url + ')'};
            let attrs =  {bgUrl: url};
            if(this.isSite){
              // this.siteAttrs.bgPositionRepeatType
              // bgPositionStyle( styles, this.siteAttrs.bgPositionRepeatType)
              this.updateSiteAttrs(attrs);
              // this.updateSiteStyles(styles);
            }else{
              // bgPositionStyle( styles, this.page.attrs.bgPositionRepeatType)
              this.updatePageAttrs({attrs});
              // this.updatePageStyles(styles);
            }
          }else{
            let comAttr = this.mediaPop.comAttr;
            let picAttr = this.mediaPop.picAttr;
            let index = this.mediaPop.index;
            let qIndex = this.mediaPop.qIndex;
            if(index >= 0){
              let isInteractionData = this.mediaPop.isInteractionData;
              let data_ = {item:{}, index};
              data_.item[picAttr] = url;
              if(isInteractionData){
                let interactionData = _.cloneDeep(this.componentData.interactionData);
                if(interactionData.isDimension){
                  interactionData[comAttr][index][qIndex][picAttr] = url;
                }else{
                  interactionData[comAttr][index][picAttr] = url;
                }
                this.$store.commit("components/updateInteractionData", { interactionData });
              }else if(this.mediaPop.event && this.mediaPop.event.controlId){
                data_.controlId = this.mediaPop.event.controlId
                this.updateWbComponentItem(data_);
              }else{
                if(qIndex >= 0){
                  delete data_.item[picAttr];
                  data_.item[comAttr] = [];
                  data_.item[comAttr][qIndex] = {};
                  data_.item[comAttr][qIndex][picAttr] = url;
                  this.updateComponentItem(data_);
                }else{
                  this.updateComponentItem(data_);
                }
              }
            }else{
              let isHaveCom = comAttr && comAttr.length > 0;
              let params = {};
              if(isHaveCom){
                let comAttrs = comAttr.split(".")
                if(comAttrs.length > 1){
                  let comAttr_ = comAttrs.shift()
                  this.recursionAssignment(comAttrs.join('.'), params[comAttr_] = {}, picAttr, url)
                }else{
                  params[comAttr] = {};
                  params[comAttr][picAttr] = url;
                }
              }else{
                params[picAttr] = url;
              }
              // if(picAttr == 'bgUrl'){
                // if(isHaveCom){
                //   params[comAttr].styles = {backgroundImage: 'url('+url+')'};
                // }else{
                  // params.styles = {backgroundImage:'url('+url+')'};
                // }
              // }
              this.updateCurrentComponentData(params);
            }
          }
        }else{
          if(this.isDisplayIcon){
            e.stopPropagation();
            e.preventDefault();
            this.updateMediaItem({type: this.item.type, index, item:{isDelete:!item.isDelete}})
            return;
          }
          if(this.item.type == MEDIAS.image.type){
            this.onAddImg(e, item);
          }else if(this.item.type == MEDIAS.audio.type){
            this.onAddAudio(e, item);
          }else if(this.item.type == MEDIAS.video.type){
            this.onAddVideo(e, item);
          }
        }
      },
      recursionAssignment(comAttr, params, picAttr, url){
        let comAttrs = comAttr.split(".")
        if(comAttrs.length > 1){
          let comAttr_ = comAttrs.shift()
          this.recursionAssignment(comAttrs.join('.'), params[comAttr_] = {}, picAttr, url)
        }else{
          params[comAttr] = {}
          params[comAttr][picAttr] = url;
        }
      },
      onAddImg(e, item){
        let target = e.target;
        let url = item.url;
        let ratio = getImgRatio(target.naturalWidth, target.naturalHeight);
        let width = parseInt(target.naturalWidth * ratio);
        let height = parseInt(target.naturalHeight * ratio);
        let imgData = {cid: COMPONENT_TYPES.wb_img, commonAttr:{url}, conAttr: {width, height}};
        this.addComponent(imgData);
      },
      onAddAudio(e, item){
				let url = item.url;
				let imgData = {cid: COMPONENT_TYPES.wb_audio, commonAttr:{url}, conAttr: {width:68, height:68}};
				this.addComponent(imgData);
      },
      onAddVideo(e, item){
        let poster = item.poster ? item.poster : '';
				let url = item.url;
        let width = MOBILE_WID_HEI.width;
        let height = parseInt(width/16 * 9);
				let videoData = {cid: COMPONENT_TYPES.wb_video,commonAttr:{url, poster}, conAttr: {width, height}};
				this.addComponent(videoData);
      },
      onClose(){
        this.hiddenMediaPop();
      },
      click2ChangeGroup(group) {
        let that = this;
        that.tabGroup = group;
      },
      click2GetItem(item) {
        console.log("url: " + item.url);
        // this.$emit("getImg", item.url);
      },
      requestAnimFrame() {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {return window.setTimeout(callback, 1000 / 60);};
      },
    },
    watch: {
      site_id(){
        this.loadSiteId = parseInt(this.site_id);
      }
    },
    beforeUnmount() {
    },
  }
</script>

<style lang="scss">
  @import '@/assets/css/common.scss';
  .el-radio-button__orig-radio:checked+.el-radio-button__inner {
      color: #fff;
      background-color: var(--btn-blue);
      border-color: var(--btn-blue);
      -webkit-box-shadow: -1px 0 0 0 var(--btn-blue);
      box-shadow: -1px 0 0 0 var(--btn-blue);
      font-weight: normal;
  }
  .popover-img{
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  .width-height-100{
    width: 100%;
    height: 100%;
  }
  .media-layout{
    max-width: 760px;

    .el-pagination.is-background .el-pager li{
      height: 24px;
      line-height: 24px;
      margin: 0 3px;
      min-width: 24px;
    }

    .btn-upload{
      color: #fff;
      background-color: var(--btn-blue);
      border-color: var(--btn-blue);
      padding: 8px 26px;
      border-radius: 4px;
    }

    .el-button--primary {
      color: #fff;
      background-color: var(--btn-blue);
      border-color: var(--btn-blue);
    }
    .el-radio-button__inner{
      font-weight: normal;
      font-size: 16px;
    }
    .el-menu-item-group__title{
      padding: 7px 7px !important;
      text-align: center;
      margin-bottom: 12px;
      color: #43475C !important;
    }

    .clear-ed i{
      font-size: 24px;
    }
    .clear-ed .font-12 i{
      font-size: 12px;
    }
    .el-tabs__header{
      margin: 0;
    }
    .btn-close{
      position: absolute;
      right: 10px;
      top: 10px;
      border: none;
    }

    .media-layout-handle{
      .left{
        float: left;
      }

      .right{
        float: right;
      }

      .handle-upload{

        .handle-upload-btn{
          font-size: 14px;
          color: #fff;
          width: 118px;
          height: 30px;
          // line-height: 30px;
          text-align: center;
          background: #127BFF;
        }
        .handle-upload-btn:active{
          color: #eee;
          font-size: 13px;
        }

        .handle-upload-tips{
          font-size: 12px;
          color: #A5AFBE;
          margin-left: 12px;
        }
      }

      .handle-mg{
        height: 38px;

        .handle-mg-btn{
          font-size: 12px;
          color: #43475C;
          margin-left: 20px;
        }
      }
    }

    .media-layout-group{
      .group-tabs{
        display: flex;

        a{
          position: relative;
          // width: 68px;
          height: 16px;
          margin: 0px;
          font-size: 12px;
          color: #43475C;
          padding: 0 10px;
          border-right: 1px solid #dcdfe6;
          border-radius: 0;
          text-decoration: none;

          span{
            display: block;
            margin-top: -2px;
            padding: 0 12px;
            line-height: 20px;
            text-align: center;
            border-radius: 2px;
          }
        }
        a:first-child{
          padding-left: 0px;
        }
        a:last-child{
          border-right: none;
        }
      }

      .group-lists{
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        padding-top: 18px;
        overflow: auto;
        max-height: 362px;

        div{
          width: 98px;
          margin: 0 4px 8px 0;
          padding: 0;
          cursor: pointer;
          flex-direction: column;

          .group-item{
            width: 90px;
            height: 90px;
            background: #F3F5FA;
            position: relative;
            .group-item-con{
              width: inherit;
              height: inherit;
            }
            .el-loading-parent--relative{
              position: static;
            }

            .delete-icon{
              position: absolute;
              top: 4px;
              left: 4px;
              background-image: url('//static.hd.xxx.com/jye/fe-web/images/btn-media-unselect.png');
              width: 13px;
              height: 13px;
              background-size: contain;


              &.active{
                background-image: url('//static.hd.xxx.com/jye/fe-web/images/btn-media-select.png');
              }
            }


            p{
              text-align: center;
              font-size: 24px;
              line-height: 90px;
            }
            img{
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
            .popover-img-con{
              position: relative;
              width: inherit;
              height: inherit;

              .el-button{
                border: none;
                background-color: transparent;
                color: #fff;
              }
            }
            .popover-img-con span{
              position: absolute;
              bottom: 0;
              right: 0;
              object-fit: contain;
              line-height: 20px;
            }
          }
          .group-item-name{
            display: block;
            width: 100%;
            font-size: 11px;
            color: #43475C;
            letter-spacing: 0;
            -webkit-line-clamp: 1;
            text-align: center;
          }
        }
        li:hover{
          .group-item-name{
            color: #66b1ff;
          }
        }
      }

      .is-group{
        span{
          color: #fff !important;
          background: #127BFF;
        }
      }
    }

    .flex-end{
      display: flex;
      align-items: flex-end;
    }

    .popper__arrow {
      border-width: 6px;
      filter: drop-shadow(0 2px 12px rgba(0,0,0,.03));
    }
    .popper__arrow:after {
        bottom: -6px;
        left: 1px;
        border-right-color: #fff;
        border-left-width: 0;
    }

    .popper__arrow:after {
        content: " ";
        border-width: 6px;
    }
    .popper__arrow, .popper__arrow:after {
      position: absolute;
      display: block;
      width: 0;
      height: 0;
      border-color: transparent;
      border-style: solid;
      bottom: -6px;
      left: 1px;
      border-right-color: #fff;
      border-left-width: 0;
    }

  }
</style>
